<template>
  <div class="issuance-container">
    <div class="header-actions">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        新增出库
      </el-button>
      <div class="search-container">
        <el-input
          v-model="searchQuery"
          placeholder="请输入单号"
          class="search-input"
          @keyup.enter="handleSearch"
        />
        <el-button type="primary" @click="handleSearch">
          <el-icon><Search /></el-icon>
          搜索
        </el-button>
        <el-button @click="handleExport">
          <el-icon><Download /></el-icon>
          导出
        </el-button>
      </div>
    </div>

    <el-table
      v-loading="loading"
      :data="inventoryFlowList"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="序号" width="80" />
      <el-table-column prop="number" label="单号" width="180" />
      <el-table-column prop="status" label="操作状态" width="120">
        <template #default="scope">
          <el-tag :type="getStatusTagType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="repositoryName" label="仓库名称" width="150">
        <template #default="scope">
          {{ scope.row.rname || scope.row.repositoryName }}
        </template>
      </el-table-column>
      <el-table-column prop="repositoryBelong" label="仓库归属" width="150">
        <template #default="scope">
          {{ scope.row.cname || scope.row.repositoryBelong }}
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="操作日期" width="180" />
      <el-table-column prop="person" label="制单人" width="120">
        <template #default="scope">
          <span v-if="scope.row.person">{{ scope.row.person }}</span>
          <span v-else class="text-gray-400">--</span>
        </template>
      </el-table-column>
      <el-table-column prop="vendorId" label="供应商" width="120">
        <template #default="scope">
          {{ getVendorName(scope.row) }}
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注" min-width="100">
        <template #default="scope">
          <span v-if="scope.row.remark">{{ scope.row.remark }}</span>
          <span v-else class="text-gray-400">--</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="handleView(scope.row)">查看出库单</el-button>
          <el-button link type="primary" size="small" @click="handleEdit(scope.row)">修改</el-button>
          <el-button link type="danger" size="small" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="出库单详情" width="800px">
      <div v-if="currentDetail" class="detail-content">
        <div class="detail-header">
          <div class="detail-item">
            <span class="label">出库单号：</span>
            <span class="value">{{ currentDetail.number }}</span>
          </div>
          <div class="detail-item">
            <span class="label">制单人：</span>
            <span class="value">{{ currentDetail.person }}</span>
          </div>
        </div>
        <div class="detail-info">
          <div class="detail-item">
            <span class="label">单据日期：</span>
            <span class="value">{{ currentDetail.createTime }}</span>
          </div>
          <div class="detail-item">
            <span class="label">出库仓库：</span>
            <span class="value">{{ currentDetail.rname || currentDetail.repositoryName || '未设置' }}</span>
          </div>
          <div class="detail-item">
            <span class="label">仓库归属：</span>
            <span class="value">{{ currentDetail.cname || currentDetail.repositoryBelong || '未设置' }}</span>
          </div>
        </div>
        <div class="detail-item full-width">
          <span class="label">备注：</span>
          <span class="value">{{ currentDetail.remark || '无' }}</span>
        </div>
        <div class="material-list">
          <h3>详细出库列表</h3>
          <el-table :data="currentDetail.materialPriceList || []" style="width: 100%">
            <el-table-column prop="materialName" label="材料名称" width="150" />
            <el-table-column prop="brand" label="品牌" width="120" />
            <el-table-column prop="spec" label="规格型号" width="180" />
            <el-table-column prop="unit" label="单位" width="100" />
            <el-table-column prop="price" label="出库价" width="120" />
            <el-table-column prop="quantity" label="数量" width="120" />
            <el-table-column prop="remark" label="备注" min-width="100" />
          </el-table>
        </div>
      </div>
    </el-dialog>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="formDialogVisible" :title="isEdit ? '编辑出库单' : '新增出库单'" width="800px">
      <el-form ref="formRef" :model="formData" label-width="100px">
        <div class="form-row">
          <el-form-item label="出库单号" prop="number" :rules="[{ required: true, message: '请输入出库单号' }]">
            <el-input v-model="formData.number" placeholder="请输入出库单号" />
          </el-form-item>
          <el-form-item label="制单人" prop="person" :rules="[{ required: true, message: '请输入制单人' }]">
            <el-input v-model="formData.person" placeholder="请输入制单人" />
          </el-form-item>
        </div>
        <div class="form-row">
          <el-form-item label="出库仓库" prop="repositoryId" :rules="[{ required: true, message: '请选择出库仓库' }]">
            <el-select v-model="formData.repositoryId" placeholder="请选择出库仓库">
              <el-option v-for="repo in repositoryList" :key="repo.id" :label="repo.name" :value="repo.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="供应商" prop="vendorId">
            <el-select v-model="formData.vendorId" placeholder="请选择供应商">
              <el-option v-for="vendor in vendorList" :key="vendor.id" :label="vendor.name" :value="vendor.id" />
            </el-select>
          </el-form-item>
        </div>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" placeholder="请输入备注" type="textarea" rows="3" />
        </el-form-item>
        
        <div class="material-price-list">
          <div class="list-header">
            <h3>详细出库列表</h3>
            <el-button type="primary" size="small" @click="addMaterialItem">
              <el-icon><Plus /></el-icon>
              添加
            </el-button>
          </div>
          <el-table :data="formData.materialPriceList" style="width: 100%">
            <el-table-column prop="materialName" label="材料名称" width="150">
              <template #default="scope">
                <el-input v-model="scope.row.materialName" placeholder="请输入材料名称" />
              </template>
            </el-table-column>
            <el-table-column prop="brand" label="品牌" width="120">
              <template #default="scope">
                <el-input v-model="scope.row.brand" placeholder="请输入品牌" />
              </template>
            </el-table-column>
            <el-table-column prop="spec" label="规格型号" width="180">
              <template #default="scope">
                <el-input v-model="scope.row.spec" placeholder="请输入规格型号" />
              </template>
            </el-table-column>
            <el-table-column prop="unit" label="单位" width="100">
              <template #default="scope">
                <el-input v-model="scope.row.unit" placeholder="请输入单位" />
              </template>
            </el-table-column>
            <el-table-column prop="price" label="出库价" width="120">
              <template #default="scope">
                <el-input v-model.number="scope.row.price" placeholder="请输入出库价" type="number" />
              </template>
            </el-table-column>
            <el-table-column prop="quantity" label="数量" width="120">
              <template #default="scope">
                <el-input v-model.number="scope.row.quantity" placeholder="请输入数量" type="number" />
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" min-width="100">
              <template #default="scope">
                <el-input v-model="scope.row.remark" placeholder="请输入备注" />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80">
              <template #default="scope">
                <el-button type="danger" size="small" @click="removeMaterialItem(scope.$index)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="formDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 物料选择对话框 -->
    <el-dialog v-model="materialSelectDialogVisible" title="添加材料" width="800px">
      <div class="material-select-header">
        <el-input
          v-model="materialSearchName"
          placeholder="请输入材料名称"
          class="search-input"
          style="width: 200px; margin-right: 10px"
        />
        <el-input
          v-model="materialSearchBrand"
          placeholder="品牌"
          class="search-input"
          style="width: 200px; margin-right: 10px"
        />
        <el-button type="primary" @click="handleMaterialSearch">
          <el-icon><Search /></el-icon>
          搜索
        </el-button>
      </div>
      <el-table
        v-loading="materialLoading"
        :data="materialList"
        style="width: 100%"
        @selection-change="handleMaterialSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="材料名称" width="150" />
        <el-table-column prop="brand" label="品牌" width="120" />
        <el-table-column prop="specification" label="规格型号" width="180" />
        <el-table-column prop="unit" label="单位" width="100" />
        <el-table-column prop="stocks" label="库存数量" width="120">
          <template #default="scope">
            <span style="color: #f56c6c;">{{ scope.row.stocks || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="outboundPrice" label="建议零售价" width="120">
          <template #default="scope">
            <span>{{ scope.row.outboundPrice || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" min-width="100" />
      </el-table>
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="materialPagination.currentPage"
          v-model:page-size="materialPagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="materialPagination.total"
          @size-change="handleMaterialSizeChange"
          @current-change="handleMaterialCurrentChange"
        />
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="materialSelectDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmMaterialSelection">确定</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 确认对话框 -->
    <el-dialog v-model="confirmDialogVisible" title="确认删除" width="30%">
      <span>确定要删除选中的出库单吗？</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="confirmDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmDelete">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { Plus, Search, Download } from '@element-plus/icons-vue';
import {
  getInventoryFlowList,
  createInventoryFlow,
  updateInventoryFlow,
  deleteInventoryFlow,
  deleteBatchInventoryFlow,
  getInventoryFlowById,
  getInventoryMaterialList
} from '@/api/inventoryFlow';
import { getMaterialList, getMaterialById } from '@/api/material';
import { getVendorList } from '@/api/vendor';
import { getRepositoryList } from '@/api/repository';
import type { InventoryFlowItem, InventoryFlowListParams, InventoryFlowPayload, InventoryMaterialItem } from '@/api/inventoryFlow';
import type { MaterialItem, MaterialListParams } from '@/api/material';
import type { VendorItem } from '@/api/vendor';
import type { RepositoryItem } from '@/api/repository';

// 状态管理
const loading = ref(false);
const searchQuery = ref('');
const inventoryFlowList = ref<any[]>([]);
const selectedRows = ref<any[]>([]);

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 对话框状态
const detailDialogVisible = ref(false);
const formDialogVisible = ref(false);
const confirmDialogVisible = ref(false);
const isEdit = ref(false);
const currentDetail = ref<any>(null);
const currentDeleteId = ref<number | null>(null);
const formRef = ref<any>(null);

// 供应商和仓库列表
const vendorList = ref<VendorItem[]>([]);
const repositoryList = ref<RepositoryItem[]>([]);

// 物料选择对话框相关状态
const materialSelectDialogVisible = ref(false);
const materialList = ref<MaterialItem[]>([]);
const materialLoading = ref(false);
const materialSearchName = ref('');
const materialSearchBrand = ref('');
const selectedMaterials = ref<MaterialItem[]>([]);
const materialPagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 表单数据
const formData = reactive<InventoryFlowPayload & {
  id?: number;
  materialPriceList: Array<{
    materialId: number;
    materialName: string;
    brand: string;
    spec: string;
    unit: string;
    price: number;
    quantity: number;
    remark: string;
  }>;
}>({
  id: undefined,
  number: '',
  status: 1, // 1表示已出库
  person: '',
  repositoryId: '',
  vendorId: '',
  remark: '',
  materialPriceList: []
});

// 获取供应商列表
const fetchVendorList = async () => {
  try {
    const params = {
      page: 1,
      limit: 100 // 获取所有供应商
    };
    const response = await getVendorList(params);
    if ((response.code === 0 || response.code === 200) && response.data) {
      vendorList.value = response.data.records || response.data.list || [];
    }
  } catch (error) {
    console.error('获取供应商列表失败:', error);
  }
};

// 获取仓库列表
const fetchRepositoryList = async () => {
  try {
    const params = {
      page: 1,
      limit: 100 // 获取所有仓库
    };
    const response = await getRepositoryList(params);
    if ((response.code === 0 || response.code === 200) && response.data) {
      repositoryList.value = response.data.records || response.data.list || [];
    }
  } catch (error) {
    console.error('获取仓库列表失败:', error);
  }
};



// 获取库存流水列表（传入status=1表示出库）
const fetchInventoryFlowList = async () => {
  try {
    loading.value = true;
    const params: InventoryFlowListParams = {
      page: pagination.currentPage,
      limit: pagination.pageSize,
      query: searchQuery.value,
      status: 1 // 只获取出库记录
    };
    const response = await getInventoryFlowList(params);
    
    if ((response.code === 0 || response.code === 200) && response.data) {
      const data = response.data as any;
      
      if (data.data && data.data.records) {
        inventoryFlowList.value = data.data.records;
        pagination.total = data.data.totalRow || 0;
      } else if (data.records) {
        inventoryFlowList.value = data.records;
        pagination.total = data.totalRow || 0;
      } else if (data.list) {
        inventoryFlowList.value = data.list;
        pagination.total = data.total || 0;
      } else {
        inventoryFlowList.value = Array.isArray(data) ? data : [];
        pagination.total = 0;
      }
    }
  } catch (error) {
    console.error('获取库存流水列表失败:', error);
    ElMessage.error('获取数据失败');
  } finally {
    loading.value = false;
  }
};

// 获取物料列表
const fetchMaterialList = async () => {
  try {
    materialLoading.value = true;
    const params: MaterialListParams = {
      page: materialPagination.currentPage,
      limit: materialPagination.pageSize,
      name: materialSearchName.value
    };
    const response = await getMaterialList(params);
    if ((response.code === 0 || response.code === 200) && response.data) {
      // 直接从records获取数据，根据网络请求实际返回的结构
      materialList.value = response.data.records || response.data.list || [];
      materialPagination.total = response.data.total || 0;
    }
  } catch (error) {
    console.error('获取物料列表失败:', error);
    ElMessage.error('获取物料列表失败');
  } finally {
    materialLoading.value = false;
  }
};

// 获取供应商名称
const getVendorName = (row: any) => {
  if (row.vname) return row.vname;
  if (row.vendorName) return row.vendorName;
  
  // 如果有供应商ID，可以尝试从本地缓存的供应商列表中查找
  if (row.vendorId) {
    const vendor = vendorList.value.find(v => v.id === row.vendorId);
    if (vendor) return vendor.name;
  }
  return '未设置';
};

// 新增
const handleAdd = () => {
  isEdit.value = false;
  // 重置所有表单字段，确保没有脏数据
  formData.id = undefined;
  formData.number = '';
  formData.status = 1; // 明确设置为出库状态
  formData.person = '';
  formData.vendorId = '';
  formData.repositoryId = '';
  formData.remark = '';
  formData.materialPriceList = [];
  formDialogVisible.value = true;
};

// 编辑
const handleEdit = async (row: any) => {
  try {
    isEdit.value = true;
    const response = await getInventoryFlowById(row.id);
    if ((response.code === 0 || response.code === 200) && response.data) {
      const data = response.data as any;
      formData.id = data.id;
      formData.number = data.number;
      formData.status = data.status || 1; // 保留原状态，如果没有则默认为出库
      formData.person = data.person;
      
      // 确保出库仓库和仓库归属与列表保持一致
      // 优先使用传入的row对象中的仓库信息，这样可以保证与列表显示一致
      if (row.repositoryId) {
        formData.repositoryId = row.repositoryId;
      } else if (data.repositoryId) {
        formData.repositoryId = data.repositoryId;
      }
      
      formData.vendorId = data.vendorId;
      formData.remark = data.remark || '';
      
      // 初始化物料列表
      formData.materialPriceList = [];
      
      // 如果有物料列表，根据materialId查询物料详情
      if (data.materialPriceList && Array.isArray(data.materialPriceList)) {
        for (const item of data.materialPriceList) {
          if (item.materialId) {
            try {
              // 根据materialId查询物料详情
              const materialResponse = await getMaterialById(item.materialId);
              if ((materialResponse.code === 0 || materialResponse.code === 200) && materialResponse.data) {
                const materialData = materialResponse.data as MaterialItem;
                // 填充物料详情
                formData.materialPriceList.push({
                  materialId: item.materialId,
                  materialName: materialData.name,
                  brand: materialData.brand,
                  spec: materialData.specification,
                  unit: materialData.unit,
                  price: item.price || 0,
                  quantity: item.quantity || 0,
                  remark: item.remark || materialData.remark || ''
                });
              } else {
                // 如果查询失败，使用现有数据
                formData.materialPriceList.push({
                  materialId: item.materialId,
                  materialName: '',
                  brand: '',
                  spec: '',
                  unit: '',
                  price: item.price || 0,
                  quantity: item.quantity || 0,
                  remark: item.remark || ''
                });
              }
            } catch (materialError) {
              console.error(`获取物料ID为${item.materialId}的详情失败:`, materialError);
              // 查询失败时使用现有数据
              formData.materialPriceList.push({
                materialId: item.materialId,
                materialName: '',
                brand: '',
                spec: '',
                unit: '',
                price: item.price || 0,
                quantity: item.quantity || 0,
                remark: item.remark || ''
              });
            }
          } else {
            // 没有materialId的情况
            formData.materialPriceList.push({
              materialId: 0,
              materialName: '',
              brand: '',
              spec: '',
              unit: '',
              price: item.price || 0,
              quantity: item.quantity || 0,
              remark: item.remark || ''
            });
          }
        }
      }
      
      formDialogVisible.value = true;
    }
  } catch (error) {
    console.error('获取编辑数据失败:', error);
    ElMessage.error('获取数据失败');
  }
};

// 删除单个
const handleDelete = (id: number) => {
  currentDeleteId.value = id;
  confirmDialogVisible.value = true;
};

// 确认删除
const confirmDelete = async () => {
  try {
    if (currentDeleteId.value !== null) {
      // 删除单个
      await deleteInventoryFlow(currentDeleteId.value);
      ElMessage.success('删除成功');
      fetchInventoryFlowList();
    } else if (selectedRows.value.length > 0) {
      // 批量删除
      await deleteBatchInventoryFlow({ ids: selectedRows.value.map(row => row.id) });
      ElMessage.success('批量删除成功');
      fetchInventoryFlowList();
    }
  } catch (error) {
    console.error('删除失败:', error);
    ElMessage.error('删除失败，请稍后重试');
  } finally {
    confirmDialogVisible.value = false;
    currentDeleteId.value = null;
    selectedRows.value = [];
  }
};

// 添加物料项
const addMaterialItem = () => {
  // 检查是否已选择出库仓库
  if (!formData.repositoryId) {
    ElMessage.warning('请先选择出库仓库');
    return;
  }
  
  // 调用新API获取指定仓库的库存材料信息
  fetchInventoryMaterialList().then(() => {
    materialSelectDialogVisible.value = true;
  });
};

// 获取库存材料列表
const fetchInventoryMaterialList = async () => {
  try {
    materialLoading.value = true;
    const params = {
      page: materialPagination.currentPage,
      limit: materialPagination.pageSize,
      repositoryId: formData.repositoryId,
      name: materialSearchName.value,
      brand: materialSearchBrand.value
    };
    const response = await getInventoryMaterialList(params);
    if ((response.code === 0 || response.code === 200) && response.data) {
      // 处理返回数据，根据实际返回结构调整
      if (response.data.records) {
        materialList.value = response.data.records;
        materialPagination.total = response.data.total || 0;
      } else if (response.data.list) {
        materialList.value = response.data.list;
        materialPagination.total = response.data.total || 0;
      } else {
        materialList.value = [];
        materialPagination.total = 0;
      }
    }
  } catch (error) {
    console.error('获取库存材料列表失败:', error);
    ElMessage.error('获取库存材料列表失败');
  } finally {
    materialLoading.value = false;
  }
};

// 修改物料搜索函数，使用新的API
const handleMaterialSearch = () => {
  materialPagination.currentPage = 1;
  fetchInventoryMaterialList();
};

// 修改物料分页大小变化处理函数
const handleMaterialSizeChange = (size: number) => {
  materialPagination.pageSize = size;
  materialPagination.currentPage = 1;
  fetchInventoryMaterialList();
};

// 修改物料当前页变化处理函数
const handleMaterialCurrentChange = (page: number) => {
  materialPagination.currentPage = page;
  fetchInventoryMaterialList();
};

// 物料选择变化
const handleMaterialSelectionChange = (selection: InventoryMaterialItem[]) => {
  // 这里需要将InventoryMaterialItem类型转换为MaterialItem类型
  selectedMaterials.value = selection;
};

// 移除物料项
const removeMaterialItem = (index: number) => {
  formData.materialPriceList.splice(index, 1);
};

// 保存
const handleSave = async () => {
  if (!formRef.value) return;
  
  try {
    await formRef.value.validate();
    
    // 检查是否有物料项
    if (formData.materialPriceList.length === 0) {
      ElMessage.warning('请至少添加一个物料');
      return;
    }
    
    // 检查物料项的必填信息
    const hasEmptyRequired = formData.materialPriceList.some(item => 
      !item.price || !item.quantity
    );
    
    if (hasEmptyRequired) {
      ElMessage.warning('请填写所有物料的出库价和数量');
      return;
    }
    
    // 构建payload，按照API要求的格式
    const payload: any = {
      number: formData.number,
      status: formData.status || 1, // 使用formData中的status，默认为出库
      person: formData.person,
      repositoryId: formData.repositoryId,
      vendorId: formData.vendorId,
      remark: formData.remark,
      // 只包含API需要的字段
      materialPriceList: formData.materialPriceList.map(item => ({
        materialId: item.materialId,
        price: item.price,
        quantity: item.quantity
      }))
    };
    
    if (isEdit.value && formData.id) {
      // 更新时添加id
      const updatePayload = { ...payload, id: formData.id };
      await updateInventoryFlow(updatePayload);
      ElMessage.success('更新成功');
    } else {
      await createInventoryFlow(payload);
      ElMessage.success('创建成功');
    }
    
    formDialogVisible.value = false;
    fetchInventoryFlowList();
  } catch (error: any) {
    console.error('保存失败:', error);
    if (error.name === 'Error') {
      ElMessage.error(error.message || '保存失败，请稍后重试');
    }
  }
};

// 导出
const handleExport = () => {
  ElMessage.success('导出成功');
};

// 获取状态文本
const getStatusText = (status: number) => {
  return status === 1 ? '出库' : '入库';
};

// 获取状态标签类型
const getStatusTagType = (status: number) => {
  return status === 1 ? 'warning' : 'success';
};

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1;
  fetchInventoryFlowList();
};

// 选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection;
};

// 查看详情
const handleView = async (row: any) => {
  try {
    const response = await getInventoryFlowById(row.id);
    if ((response.code === 0 || response.code === 200) && response.data) {
      const detailData = response.data as any;
      
      // 优先使用传入的row对象中的信息，确保与列表显示一致
      // 创建一个新对象，避免直接修改响应数据
      const formattedDetail = {
        ...detailData,
        // 供应商信息 - 优先使用row对象中的信息
        vname: row.vname || detailData.vname || '',
        vendorName: row.vendorName || detailData.vendorName || getVendorName(row),
        vendorId: row.vendorId || detailData.vendorId,
        
        // 仓库信息 - 优先使用row对象中的信息
        rname: row.rname || detailData.rname || '',
        repositoryName: row.repositoryName || detailData.repositoryName || '',
        cname: row.cname || detailData.cname || '',
        repositoryBelong: row.repositoryBelong || detailData.repositoryBelong || '',
        repositoryId: row.repositoryId || detailData.repositoryId,
        
        // 其他基本信息
        number: row.number || detailData.number || '',
        person: row.person || detailData.person || '',
        createTime: row.createTime || detailData.createTime || '',
        remark: row.remark || detailData.remark || '',
        
        // 初始化物料列表
        materialPriceList: []
      };
      
      // 如果有物料列表，根据materialId查询物料详情
      if (detailData.materialPriceList && Array.isArray(detailData.materialPriceList)) {
        for (const item of detailData.materialPriceList) {
          if (item.materialId) {
            try {
              // 根据materialId查询物料详情
              const materialResponse = await getMaterialById(item.materialId);
              if ((materialResponse.code === 0 || materialResponse.code === 200) && materialResponse.data) {
                const materialData = materialResponse.data as MaterialItem;
                // 填充物料详情
                formattedDetail.materialPriceList.push({
                  materialId: item.materialId,
                  materialName: materialData.name,
                  brand: materialData.brand,
                  spec: materialData.specification,
                  unit: materialData.unit,
                  price: item.price || 0,
                  quantity: item.quantity || 0,
                  remark: item.remark || materialData.remark || ''
                });
              } else {
                // 如果查询失败，使用现有数据
                formattedDetail.materialPriceList.push({
                  materialId: item.materialId,
                  materialName: item.materialName || '',
                  brand: item.brand || '',
                  spec: item.spec || '',
                  unit: item.unit || '',
                  price: item.price || 0,
                  quantity: item.quantity || 0,
                  remark: item.remark || ''
                });
              }
            } catch (materialError) {
              console.error(`获取物料ID为${item.materialId}的详情失败:`, materialError);
              // 查询失败时使用现有数据
              formattedDetail.materialPriceList.push({
                materialId: item.materialId,
                materialName: item.materialName || '',
                brand: item.brand || '',
                spec: item.spec || '',
                unit: item.unit || '',
                price: item.price || 0,
                quantity: item.quantity || 0,
                remark: item.remark || ''
              });
            }
          } else {
            // 没有materialId的情况
            formattedDetail.materialPriceList.push({
              materialId: 0,
              materialName: item.materialName || '',
              brand: item.brand || '',
              spec: item.spec || '',
              unit: item.unit || '',
              price: item.price || 0,
              quantity: item.quantity || 0,
              remark: item.remark || ''
            });
          }
        }
      }
      
      currentDetail.value = formattedDetail;
      detailDialogVisible.value = true;
    }
  } catch (error) {
    console.error('获取详情失败:', error);
    ElMessage.error('获取详情失败');
  }
};

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  fetchInventoryFlowList();
};

// 当前页变化
const handleCurrentChange = (page: number) => {
  pagination.currentPage = page;
  fetchInventoryFlowList();
};

// 确认物料选择
const confirmMaterialSelection = async () => {
  for (const material of selectedMaterials.value) {
    try {
      // 注意：InventoryMaterialItem中的id实际上是库存记录ID，而不是物料ID
      // 正确的物料ID应该是materialId字段
      const inventoryMaterial = material as InventoryMaterialItem;
      const existingIndex = formData.materialPriceList.findIndex(item => item.materialId === inventoryMaterial.materialId);
      
      if (existingIndex === -1) {
        // 使用materialId查询物料详情，确保获取最新的物料信息
        const materialResponse = await getMaterialById(inventoryMaterial.materialId);
        
        if ((materialResponse.code === 0 || materialResponse.code === 200) && materialResponse.data) {
          const materialData = materialResponse.data as MaterialItem;
          formData.materialPriceList.push({
            materialId: inventoryMaterial.materialId,
            materialName: materialData.name,
            brand: materialData.brand,
            spec: materialData.specification,
            unit: materialData.unit,
            price: inventoryMaterial.outboundPrice || 0, // 使用建议零售价作为默认价格
            quantity: 0,
            remark: materialData.remark || ''
          });
        } else {
          // 查询失败时使用现有数据
          formData.materialPriceList.push({
            materialId: inventoryMaterial.materialId,
            materialName: inventoryMaterial.name, // 使用模板中显示的name属性
            brand: inventoryMaterial.brand,
            spec: inventoryMaterial.specification,
            unit: inventoryMaterial.unit,
            price: inventoryMaterial.outboundPrice || 0,
            quantity: 0,
            remark: inventoryMaterial.remark || ''
          });
        }
      }
    } catch (error) {
      console.error(`处理物料ID为${material.materialId}时出错:`, error);
      // 错误情况下也添加物料，确保用户操作不中断
      formData.materialPriceList.push({
        materialId: material.materialId,
        materialName: material.name || '',
        brand: material.brand || '',
        spec: material.specification || '',
        unit: material.unit || '',
        price: material.outboundPrice || 0,
        quantity: 0,
        remark: material.remark || ''
      });
    }
  }
  materialSelectDialogVisible.value = false;
  selectedMaterials.value = [];
};

// 初始加载
onMounted(() => {
  fetchInventoryFlowList();
  fetchVendorList();
  fetchRepositoryList();
});
</script>

<style scoped>
.issuance-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
}

.header-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-container {
  display: flex;
  gap: 10px;
}

.search-input {
  width: 300px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.detail-content {
  padding: 20px 0;
}

.detail-header {
  display: flex;
  gap: 40px;
  margin-bottom: 20px;
}

.detail-info {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-bottom: 20px;
}

.detail-item {
  display: flex;
  align-items: flex-start;
  min-width: 200px;
}

.detail-item.full-width {
  min-width: 100%;
}

.label {
  font-weight: bold;
  margin-right: 10px;
  min-width: 80px;
}

.material-list {
  margin-top: 30px;
}

.material-list h3 {
  margin-bottom: 15px;
  font-size: 16px;
}

.form-row {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.form-row > .el-form-item {
  flex: 1;
}

.material-price-list {
  margin-top: 30px;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.list-header h3 {
  font-size: 16px;
  margin: 0;
}

.material-select-header {
  margin-bottom: 16px;
  display: flex;
  align-items: center;
}
</style>